package com.mk.cloud.common.interceptor.header;

import act.app.ActionContext;
import act.event.ActEvent;
import act.event.EventBus;
import act.event.On;
import act.util.Global;
import com.alibaba.fastjson.JSON;
import com.mk.cloud.common.domain.CpRequestHistory;
import com.mk.cloud.common.util.DateUtils;
import com.mk.cloud.common.util.S2;
import org.osgl.inject.annotation.Provided;
import org.osgl.mvc.annotation.Before;
import org.osgl.util.C;
import org.osgl.util.S;
import org.osgl.web.util.UserAgent;

import javax.inject.Inject;
import java.util.Date;
import java.util.Map;

public class GlobalRequest {

    @Inject
    private CpRequestHistory.Mapper cpRequestHistoryMapper;

    @Before
    @Global
    public void get(@Provided EventBus eventBus) {
        ActionContext context = ActionContext.current();
        UserAgent ua = context.req().userAgent();
        Map<String,String> map = C.map(
                "id", S2.UUID(),
                "ip", context.req().ip(),
                "path",context.req().path(),
                "os", S.eq(ua.getOS().name(), "DROID") ? "ANDROID" : ua.getOS().name(),
                "time", DateUtils.formatTimeNow(DateUtils.DEFAULT_TIME_FORMAT),
                "timestamps",new Date().getTime(),
                "device", S.eq(ua.getDevice().name(), "DROID") ? "ANDROID" : ua.getDevice().name(),
                "browser", ua.getBrowser().name(),
                "params", JSON.toJSONString(context.allParams()));
        eventBus.triggerAsync("async-add-request-params",new ActEvent<>(map));
    }


    @On(value = "async-add-request-params", async = true)
    public void addAllProductEvent(ActEvent<Map> event){
        try{
            CpRequestHistory history = JSON.parseObject(JSON.toJSONString(event.source()),CpRequestHistory.class);
            cpRequestHistoryMapper.insert(history);
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }
}
